package com.fhnew.app.ui.activity.recomend.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.ResALLGames;
import com.fhnew.app.model.network.entity.req.ResRecode;

import com.fhnew.app.util.DoubleDatePickerDialog;
import com.fhnew.app.widget.MyRecyclerView;
import com.fhnew.app.util.OnEndLessScrollListener;
import com.fhnew.app.util.OnItemClickListener;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/9/25.
 */

public class CommissionlistFragment extends Fragment {

    private TextView commissionliststarttime;
    private TextView commissionlistendtime;
    private NiceSpinner spinner;
    private TextView commissionlistsearch;
    private TextView commissionlistclear;
    private MyRecyclerView commissionlist;
    private TextView commissionlistmoney;

    private String starttime;
    private String endtime;
    View mHeaderView;
    //    ArrayList<String> list = new ArrayList<>();
    ArrayList<ResRecode.DataBean> dataBeans = new ArrayList<>();
    ArrayList<String> spinnerBeans = new ArrayList<>();
    ArrayList<String> spinnerid = new ArrayList<>();
    Adapter adapter;
    private String apinnerpostion = "";

    private boolean speenerflag = true;
    private TextView upmonth;
    private TextView tomonth;
    private TextView tosweek;
    private TextView commissionlistyestodey;
    private TextView commissionlistgetmoney;
    private TextView suucusnumber;
    private TextView succesmoney;

    private int page;//初始页数

    private OnEndLessScrollListener onEndLessScrollListener;

    private void initView (View view) {

        commissionliststarttime = view.findViewById(R.id.commissionliststarttime);
        commissionlistendtime = view.findViewById(R.id.commissionlistendtime);
        spinner = view.findViewById(R.id.spinner);
        commissionlistsearch = view.findViewById(R.id.commissionlistsearch);
        commissionlistclear = view.findViewById(R.id.commissionlistclear);
        commissionlist = view.findViewById(R.id.commissionlist);
        commissionlistmoney = view.findViewById(R.id.commissionlistmoney);

        commissionliststarttime.setOnClickListener(onClickListener);
        commissionlistendtime.setOnClickListener(onClickListener);
        commissionlistsearch.setOnClickListener(onClickListener);
        commissionlistclear.setOnClickListener(onClickListener);

    }

    @Nullable
    @Override
    public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        container = (ViewGroup) inflater.inflate(R.layout.commissionlistlayout, null);
        initView(container);
        return container;
    }

    @Override
    public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化控件
        commissionlist.setNestedScrollingEnabled(false);
        page = 0;


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        onEndLessScrollListener = new OnEndLessScrollListener(linearLayoutManager) {
            @Override
            public void getMoreData (int currentPage) {
                //下拉加载的时候页数加1
                commissionlist(++page);
            }
        };
        linearLayoutManager = new LinearLayoutManager(getContext());
        commissionlist.setLayoutManager(linearLayoutManager);
        mHeaderView = View.inflate(getContext(), R.layout.commissionlistlayoutheader, null);
        //初始化头部布局
        InitHeaderView();
        commissionlist.addHeaderView(mHeaderView);

        adapter = new Adapter();
        commissionlist.setAdapter(adapter);
        commissionlist.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

        //添加滑动监听
        commissionlist.addOnScrollListener(onEndLessScrollListener);
    }

    @Override
    public void onHiddenChanged (boolean hidden) {
        super.onHiddenChanged(hidden);
        commissionlist(page);
    }

    private void commissionlist (int page) {
        HttpJsonUtils.getHttpApiInstance()
                .getrecode(Constants.getuseAdress() + "api/m/promotion/recode", page + "", "10", starttime, endtime, apinnerpostion, UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<ResRecode>(CommissionlistFragment.this) {
                .subscribe(new CustomObserver<ResRecode>() {
                    @Override
                    protected void onCustomNext (ResRecode resRecode) {
                        try {
                            if (resRecode.code == 0) {
                                if (speenerflag) {
                                    spinnerBeans.clear();
                                    spinnerid.clear();
                                    int a = resRecode.aReStatus.size() + 1;
                                    for (int i = 0; i < a; i++) {
                                        if (i == 0) {
                                            spinnerBeans.add("全部状态");
                                            spinnerid.add("");
                                        } else {
                                            spinnerBeans.add(resRecode.aReStatus.get(i - 1).name);
                                            spinnerid.add(resRecode.aReStatus.get(i - 1).id + "");
                                        }
                                    }
                                    spinner.attachDataSource(spinnerBeans);
                                    speenerflag = false;
                                }
                                spinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
                                    @Override
                                    public void onItemSelected (NiceSpinner parent, View view, int position, long id) {
                                        apinnerpostion = spinnerid.get(position) + "";
                                    }
                                });
                                dataBeans.clear();
                                dataBeans.addAll(resRecode.data);
                                adapter.notifyDataSetChanged();
                                upmonth.setText("上月:  " + resRecode.otherData.lastMonthMoney);
                                tomonth.setText("本月:  " + resRecode.otherData.monthMoney);
                                tosweek.setText("本周:  " + resRecode.otherData.weekMoney);
                                commissionlistyestodey.setText("昨日:  " + resRecode.otherData.yesterdayMoney);
                                commissionlistgetmoney.setText("提款笔数:  " + resRecode.otherData.receiveCount);
                                succesmoney.setText("成功数:  " + resRecode.otherData.successMoney);
                                suucusnumber.setText("成功金额:  " + resRecode.otherData.successCount);

                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });
    }


    private void InitHeaderView () {
        upmonth = (TextView) mHeaderView.findViewById(R.id.upmonth);
        tomonth = (TextView) mHeaderView.findViewById(R.id.tomonth);
        tosweek = (TextView) mHeaderView.findViewById(R.id.tosweek);
        commissionlistyestodey = (TextView) mHeaderView.findViewById(R.id.commissionlistyestodey);
        commissionlistgetmoney = (TextView) mHeaderView.findViewById(R.id.commissionlistgetmoney);
        suucusnumber = (TextView) mHeaderView.findViewById(R.id.suucusnumber);
        succesmoney = (TextView) mHeaderView.findViewById(R.id.succesmoney);

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            switch (view.getId()) {
                case R.id.commissionliststarttime:
                    Calendar c = Calendar.getInstance();
                    new DoubleDatePickerDialog(getContext(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet (DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                               int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                               int endDayOfMonth) {
                            commissionliststarttime.setText("开始时间：" + startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth);
                            starttime = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                        }
                    }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), false).show();
                    break;
                case R.id.commissionlistendtime:
                    Calendar c2 = Calendar.getInstance();
                    new DoubleDatePickerDialog(getContext(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet (DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                               int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                               int endDayOfMonth) {
                            commissionlistendtime.setText("结束时间：" + startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth);
                            endtime = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                        }
                    }, c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DATE), false).show();
                    break;
                case R.id.commissionlistsearch:
                    commissionlist(page);
                    break;
                case R.id.commissionlistclear:
                    starttime = "";
                    endtime = "";
                    commissionliststarttime.setText("开始时间");
                    commissionlistendtime.setText("结束时间");
                    break;
            }
        }
    };




    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @NonNull
        @Override
        public Adapter.MViewHolder onCreateViewHolder (@NonNull ViewGroup viewGroup, int viewType) {
            return new Adapter.MViewHolder(LayoutInflater.from(getContext())
                    .inflate(R.layout.mycommissionitem, viewGroup, false));
        }

        @Override
        public void onBindViewHolder (@NonNull MViewHolder mViewHolder, int i) {
            if (i % 2 != 0) {
                mViewHolder.mycommissionitem.setBackgroundResource(R.color.blue);
            } else {
                mViewHolder.mycommissionitem.setBackgroundResource(R.color.royalblue);
            }
            mViewHolder.mycommissiontime.setText(dataBeans.get(i).belongTime);
            mViewHolder.mycommissionmoney.setText(dataBeans.get(i).order_id);
            mViewHolder.mycommissionnum.setText(dataBeans.get(i).money);
            for (int a = 0; a < spinnerid.size(); a++) {
                if (!TextUtils.isEmpty(spinnerid.get(a))) {
                    if (dataBeans.get(i).receive_status.equals(spinnerid.get(a))) {
                        mViewHolder.more.setText(spinnerBeans.get(a));
                    }
                }

            }
        }

        @Override
        public int getItemCount () {
            return dataBeans.size();
        }

        @Override
        public void onItemClick (View view, int position) {

        }

        public class MViewHolder extends RecyclerView.ViewHolder {
            LinearLayout mycommissionitem;
            TextView mycommissiontime, mycommissionmoney, mycommissionnum, more;

            MViewHolder (View itemView) {
                super(itemView);
                mycommissionitem = (LinearLayout) itemView.findViewById(R.id.mycommissionitem);
                mycommissiontime = (TextView) itemView.findViewById(R.id.mycommissiontime);
                mycommissionmoney = (TextView) itemView.findViewById(R.id.mycommissionmoney1);
                mycommissionnum = (TextView) itemView.findViewById(R.id.mycommissionnum);
                more = (TextView) itemView.findViewById(R.id.more);
            }
        }
    }

    public static void format (TextView tv) {
        if (tv != null) {
            if (!tv.getText().toString().contains(".")) {
                tv.append(".00");
            } else {
                String[] split = tv.getText().toString().split("\\.");
                switch (split.length) {
                    case 1:
                        tv.setText(split[0] + ".00");
                        break;
                    case 2:
                        tv.setText(split[0] + ".");
                        switch (split[1].length()) {
                            case 1:
                                tv.append(split[1] + "0");
                                break;
                            case 2:
                                tv.append(split[1]);
                                break;
                            default:
                                if (split[1].length() > 1)
                                    tv.append(split[1].substring(0, 2));
                                break;
                        }
                        break;
                }
            }
        }
    }
}
